package com.hcj.springcloud.service;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程:倒计时器
 * <br>
 * 做多任务并行执行，即主程序执行要等待子线程全部完成后，才同一执行
 */
public class CountDownLatchDemo implements Runnable {
    static final CountDownLatch countDownLatch = new CountDownLatch(10);


    @Override
    public void run() {
        try {
            int sleepTime = new Random().nextInt(10)* 1000;
            Thread.sleep(sleepTime);
            System.out.println(Thread.currentThread().getName()+" \t---->task complete!" + "sleepTime:"+sleepTime/1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo();
            executorService.execute(countDownLatchDemo);
        }
        // latch.await()方法要求主线程等待所有10个检查任务全部准备好才一起并行执行
        countDownLatch.await();
        System.out.println("all task complete!");
        executorService.shutdown();
    }
}
